package listbyorder.access001_100.test32;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/30 10:53
 */
public class Solution4 {

    // 神奇的解法
    public int longestValidParentheses(String s) {
        int left = 0, right = 0;
        char[] chars = s.toCharArray();
        int maxLen = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxLen = Math.max(maxLen, left * 2);
            } else if (left < right) {
                left = right = 0;
            }
        }
        left = right = 0;
        // 反向再来一遍
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == ')') {
                right++;
            } else {
                left++;
            }
            if (left == right) {
                maxLen = Math.max(maxLen, left * 2);
            } else if (left > right) {
                left = right = 0;
            }
        }
        return maxLen;
    }
}
